package com.aliang.shopping.util;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Objects;

/**
 * 请求工具类
 */
@Slf4j
@Component
public class RequestUtil {


    private static final String DB_PATH = "/data/ip2region.xdb";
    private static Searcher searcher;

    @PostConstruct
    public void init() {
        try {
            // 从类路径加载资源文件
            ClassPathResource resource = new ClassPathResource(DB_PATH);
            // 将资源文件复制到临时文件
            Path tempDbPath = Files.createTempFile("ip2region", ".xdb");
            Files.copy(resource.getStream(), tempDbPath, StandardCopyOption.REPLACE_EXISTING);
            // 使用临时文件初始化 Searcher 对象
            searcher = Searcher.newWithFileOnly(tempDbPath.toString());
            log.info("IpRegionUtil initialization success");
        } catch (Exception e) {
            log.error("IpRegionUtil initialization ERROR, {}", e.getMessage());
        }
    }

    /**
     * 获取客户端IP
     *
     * @param request
     * @return
     */
    public String getClientIP(HttpServletRequest request) {
        String clientIP = ServletUtil.getClientIP(request);
        //回环地址，读取网卡本地IP
        if ("127.0.0.1".equals(clientIP) || "0:0:0:0:0:0:0:1".equals(clientIP)) {
            try {
                return InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                log.error("InetAddress.getLocalHost()-error, {}", e.getMessage());
            }
            return null;
        }
        return clientIP;
    }

    /**
     * 根据IP地址获取地理位置信息
     *
     * @param ip IP地址
     * @return 地理位置信息
     */
    public String getRegion(String ip) {
        if (searcher == null) {
            log.error("Searcher is not initialized");
            return "未知";
        }
        try {
            String search = searcher.search(ip);
            if (Objects.equals("0|0|0|内网IP|内网IP", search)) {
                return "内网IP";
            }
            return search;
        } catch (Exception e) {
            log.error("IpRegionUtil ERROR, {}", e.getMessage());
            return "未知";
        }
    }

    @Data
    @Builder
    public static class UA {
        String os;
        String browser;
    }

    /**
     * 获取浏览器UA信息
     *
     * @param request
     * @return
     */
    public UA getUa(HttpServletRequest request) {
        String userAgent = ServletUtil.getHeaderIgnoreCase(request, "User-Agent");
        UserAgent ua = UserAgentUtil.parse(userAgent);
        return UA.builder().os(ua.getOs().toString()).browser(ua.getBrowser().toString()).build();
    }

}
